package com.nanjia.boot.common.excelhandler;

import cn.idev.excel.metadata.Head;
import cn.idev.excel.write.merge.AbstractMergeStrategy;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import java.lang.reflect.Field;
import java.util.*;

/**
 * 支持多列合并的Excel单元格合并策略
 */
public class MultiColumnMergeStrategy extends AbstractMergeStrategy {

    private Map<Integer, List<Integer>> columnGroupMap = new HashMap<>();
    private Class<?> dtoClass;
    private List<?> dataList;
    private Integer startRowIndex;

    // 记录已处理的列，避免重复处理
    private Set<Integer> processedColumns = new HashSet<>();

    public MultiColumnMergeStrategy(Class<?> dtoClass, List<?> dataList) {
        this.dtoClass = dtoClass;
        this.dataList = dataList;
        initColumnGroups();
    }

    /**
     * 初始化所有需要合并的列及其分组信息
     */
    private void initColumnGroups() {
        try {
            Field[] fields = dtoClass.getDeclaredFields();
            for (int colIndex = 0; colIndex < fields.length; colIndex++) {
                Field field = fields[colIndex];
                if (field.isAnnotationPresent(ExcelMergeColumn.class)) {
                    ExcelMergeColumn annotation = field.getAnnotation(ExcelMergeColumn.class);
                    if (annotation.strategy() == ExcelMergeColumn.MergeStrategy.VERTICAL) {
                        field.setAccessible(true);
                        List<String> columnValues = new ArrayList<>();

                        for (Object data : dataList) {
                            Object value = field.get(data);
                            columnValues.add(value != null ? value.toString() : "");
                        }

                        List<Integer> groupCounts = getGroupCountList(columnValues);
                        columnGroupMap.put(colIndex, groupCounts);
                    }
                }
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException("初始化列合并信息失败", e);
        }
    }

    /**
     * 计算合并分组
     */
    private List<Integer> getGroupCountList(List<String> columnValues) {
        if (CollectionUtils.isEmpty(columnValues)) {
            return new ArrayList<>();
        }

        List<Integer> groupCountList = new ArrayList<>();
        int count = 1;

        for (int i = 1; i < columnValues.size(); i++) {
            if (Objects.equals(columnValues.get(i), columnValues.get(i - 1))) {
                count++;
            } else {
                groupCountList.add(count);
                count = 1;
            }
        }
        groupCountList.add(count);
        return groupCountList;
    }

    @Override
    protected void merge(Sheet sheet, Cell cell, Head head, Integer relativeRowIndex) {
        if (startRowIndex == null) {
            startRowIndex = cell.getRowIndex();
            return;
        }

        int currentColumn = cell.getColumnIndex();
        int currentRow = cell.getRowIndex();

        // 只处理需要合并的列，且未处理过的
        if (columnGroupMap.containsKey(currentColumn) && !processedColumns.contains(currentColumn)) {
            mergeColumn(sheet, currentColumn);
            processedColumns.add(currentColumn);
        }
    }

    /**
     * 合并指定列
     */
    private void mergeColumn(Sheet sheet, int columnIndex) {
        List<Integer> groupCounts = columnGroupMap.get(columnIndex);
        int rowCount = startRowIndex;

        for (Integer count : groupCounts) {
            if (count > 1) {
                // 合并单元格
                CellRangeAddress cellRange = new CellRangeAddress(
                        rowCount, rowCount + count - 1, columnIndex, columnIndex
                );
                sheet.addMergedRegionUnsafe(cellRange);
            }
            rowCount += count;
        }
    }
}